import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw,
  Router,
} from "vue-router";
import CommonRouter from "./modules/common";
import ChartsRouter from "./modules/charts";
import DataScreenRouter from "./modules/dataScreen";
import TableRouter from "./modules/table";
import NestedRouter from "./modules/nested";
import FuncRouter from "./modules/func";
import ExcelRouter from "./modules/excel";
import FormRouter from "./modules/form";
import SystemRouter from "./modules/system";
import LinkRouter from "./modules/link";

import { message } from "ant-design-vue";

interface IExtendRoute {
  hidden?: boolean;
}

export const constantRoutes: Array<RouteRecordRaw & IExtendRoute> = [
  {
    path: "/login",
    name: "login",
    component: () => import('@/views/login/index.vue'),
  },
  {
    path: "/",
    name: "layout",
    component: () => import('@/layout/index.vue'),
    redirect: "/home",
    children: [
      {
        path: "/home",
        component: () => import('@/views/home/index.vue'),
        name: "home",
        meta: {
          title: "首页",
          roles: ["super", "admin"],
        },
      },
      {
        path: "/chat",
        component: () => import("@/views/chat/chat.vue"),
        name: "chat",
        meta: {
          title: "聊天框",
          roles: ["super"],
        },
      },
    ],
  },
  ...ChartsRouter,
  ...DataScreenRouter,
  ...TableRouter,
  ...CommonRouter,
  ...NestedRouter,
  ...FuncRouter,
  ...ExcelRouter,
  ...FormRouter,
  ...SystemRouter,
  ...LinkRouter,
  // ...ChatRouter,
  {
    path: "/403",
    hidden: true,
    name: "403",
    meta: {
      title: "403",
    },
    component: () => import("@/views/func/403.vue"), //这个是我自己的路径
  },
  {
    path: "/:catchAll(.*)",
    hidden: true,
    name: "404",
    meta: {
      title: "404",
    },
    component: () => import("@/views/func/404.vue"), //这个是我自己的路径
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
});
router.beforeEach((to, from, next) => {
  let roules = JSON.parse(localStorage.getItem("userInfo") || "{}").roles || [];
  if (to.path.includes("login") || to.name === "404" || to.name === "403") {
    next();
    return;
  }
  if (!roules.length) {
    message.info({ content: "请先登录" });
    next({ name: "login" });
    return;
  }
  if (
    roules.length &&
    to.meta.roles &&
    (to.meta.roles as Array<String>).includes(roules[0])
  ) {
    next();
    return;
  }
  next({ name: "403" });
});
export default router;
